package com.mazaiting.web.customize.time.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * 计算方法执行时间实现
 *
 * @author mazaiting
 * @create_time 2022/10/11 10:19
 */
@Slf4j
@Aspect
@Component
public class CostTimeAspect {

    /**
     * 计算方法耗时具体时间
     * @param joinPoint 切点
     * @return 方法返回值
     */
    @Around("@annotation(com.mazaiting.web.customize.time.CostTime)")
    public Object costTimeAround(ProceedingJoinPoint joinPoint) {
        Object obj = null;
        try {
            // 存储开始时间
            long beginTime = System.currentTimeMillis();
            //获取方法名称
            String method = joinPoint.getSignature().getName();
            //获取类名称
            String className = joinPoint.getSignature().getDeclaringTypeName();
            // 执行具体方法
            obj = joinPoint.proceed();
            //计算耗时
            long cost = System.currentTimeMillis() - beginTime;
            log.info("类:[{}]，方法:[{}] 接口耗时:[{}]", className, method, cost + "毫秒");
        } catch (Throwable throwable) {
            log.error("计算方法耗时失败: {}.", throwable.getMessage());
        }
        return obj;
    }
}
